#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import requests
import urllib.request
import urllib.parse
from http import cookiejar
import json

"""
mmtvip 登录
loginUrl: https://www.mmtvip.com/login ajax-post
"""
headers = {'Accept': '*/*',
           'Accept-Language': 'zh-CN,zh;q=0.9',
           'User-Agent': 'Mozilla/5.0 (Windows NT 6.3;'
                         'Win64; x64) AppleWebKit/537.36'
                         '(KHTML, like Gecko)Chrome/48.0'
                         '.2564.48 Safari/537.36',
           'X-Requested-With': 'XMLHttpRequest',
           'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
           }

value = {
    'name': '18658736660',
    'password': 'mmtCm1993@'
}

# # 声明一个 CookieJar 对象示例来保存 cookie
# cookie = cookiejar.CookieJar()
# # 利用 urllib库中的 request 的 HTTPCookieProcessor 对象来创建 cookie 处理器
# handler = urllib.request.HTTPCookieProcessor(cookie)
#
# # 通过 handler 来创建 opener
# opener = urllib.request.build_opener(handler)
# data = urllib.parse.urlencode(value).encode('utf8')
# request = urllib.request.Request('https://www.mmtvip.com/login', data=data, headers=headers)

# 建立一个回话,把同一用户的不同请求联系起来
session = requests.Session()


# session.cookies = cookiejar.LWPCookieJar('cookie')
#
# try:
#     session.cookies.load(ignore_discard=True)
# except IOError:
#     print('cookie 未 load')


# 登录
def mmt_login(username, password):
    data = {'name': username, 'password': password}
    data = urllib.parse.urlencode(data).encode('utf8')
    request = urllib.request.Request('https://www.mmtvip.com/login', data=data, headers=headers)
    result = session.post(request)
    session.cookies.save(ignore_discard=True, ignore_expires=True)


def is_login():
    url = "https://www.mmtvip.com/login"
    login_code = session.get(url, headers=headers, allow_redirects=False).status_code
    if 302 == login_code:
        return True
    else:
        return False


# else:
#     return False


# response = opener.open(request)


if __name__ == '__main__':
    if is_login():
        print("已经登录")

    else:
        username = input('输入账号:')
        password = input('输入密码:')
        mmt_login(username, password)
